package tu.java.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadUtil {
	
	
	
	public List uploadFiles(HttpServletRequest request) throws Exception {
		List rqInformation = new ArrayList();
		Map<String, String> formFields = null;
		Vector<Map> uploadedFiles = null;
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			FileItemFactory fFactory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(fFactory);
			List items = null;
			try {
				items = upload.parseRequest(request);
			}
			catch (FileUploadException e) {
				e.printStackTrace();
				throw new Exception("Problem with uploading file");
			}
			
			Iterator itr = items.iterator();
			formFields = new HashMap<String, String>();
			uploadedFiles = new Vector<Map>();
			int i = 0;
			while (itr.hasNext()) {
				FileItem fItem = (FileItem) itr.next();
				if (fItem.isFormField()) {
					String fieldName = fItem.getFieldName();
					String fieldValue = fItem.getString("UTF-8").trim();
					formFields.put(fieldName, fieldValue);
				}
				else if (!fItem.isFormField() && fItem.getSize() > 0) {
					Map uploadedFile = new HashMap();
					uploadedFile.put("fileName", fItem.getName());
					uploadedFile.put("fileSize", String.valueOf(fItem.getSize()));
					uploadedFile.put("mimeType", fItem.getContentType());
					uploadedFile.put("fileContent", fItem.get());
					uploadedFiles.add(i, uploadedFile);
					i++;
				}
			}
		}
		rqInformation.add(0, formFields);
		rqInformation.add(1, uploadedFiles);
		return rqInformation;
	}
	
	
	
	public Map<String, String> mapStringArrToMapString(Map<String, String[]> map) {
		
		Map<String, String> strMap = new HashMap<String, String>();
		Iterator iter = map.keySet().iterator();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			strMap.put(key, map.get(key)[0]);
		}
		return strMap;
	}
	
}
